import 'package:flutter/material.dart';
import 'package:rxdart/rxdart.dart';

/// PublishSubjects
// 和StreamControllers的行为很像，也支持多个监听，默认是sync是false，
// 也就是说里面是一个AsyncBroadcastStreamController 异步广播流
// https://blog.csdn.net/jielundewode/article/details/94381616
class PublishSubjectDemoHome extends StatefulWidget {
  const PublishSubjectDemoHome({Key? key}) : super(key: key);

  @override
  _PublishSubjectDemoHomeState createState() => _PublishSubjectDemoHomeState();
}

class _PublishSubjectDemoHomeState extends State<PublishSubjectDemoHome> {
  // 可以与bloc结合在一起使用
  PublishSubject<String> _subject = PublishSubject<String>();

  /// 用于演示监听的区别
  var _testSubject = PublishSubject<String>();

  @override
  void initState() {
    super.initState();
    // 第一个监听
    _testSubject.listen((event) => print("listener-1: $event"));
    _testSubject.add("item1");

    // 第二个监听
    _testSubject.listen((event) => print("listener-2: ${event.toUpperCase()}"));
    _testSubject.add("Item2");
    _testSubject.add("Item3");
  }

  @override
  void dispose() {
    super.dispose();
    _subject.close();
    _testSubject.close();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("PublishSubjectDemo"),
      ),
      body: Center(
        child: StreamBuilder(
          initialData: "loading...",
          stream: _subject,
          builder: (context, snapshot) {
            print("${snapshot.connectionState} - ${snapshot.data}");
            return Text("${snapshot.data}");
          },
        ),
      ),
      floatingActionButton: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          FloatingActionButton(
            heroTag: 'add',
            onPressed: () {
              _subject.add("do add action");
            },
            child: Icon(Icons.add),
          ),
          SizedBox(
            height: 10,
          ),
          FloatingActionButton(
            heroTag: 'publish',
            onPressed: () {
              _subject.add("publish artice");
            },
            child: Icon(Icons.publish),
          )
        ],
      ),
    );
  }
}
